package com.leo.ktvplayer.util;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by LeoLu on 2017/5/11.
 */

public class EssayHandlerTask {

    private OnSmartCallBack onSmartCallBack;
    private Map<Integer,EssayRunnable> runnableMap = new HashMap<>();
    private Handler handler;


    public EssayHandlerTask(){
        Create(null);
    }

    /**
     * the private method use to create handler obj
     * @param looper
     */
    private void Create(Looper looper){
        if (looper == null) {
            handler = new Handler();
        } else {
            handler = new Handler(looper);
        }

    }


    /**
     * Post delayed to handler
     * @param time
     * @param action
     */
    public synchronized void postDelayed(int time,int action){
        EssayRunnable runnable = new EssayRunnable(action) {
            @Override
            public void call() {
                if (onSmartCallBack == null)
                    throw new RuntimeException("OnSmartCallBack can't be null");
                runnableMap.remove(action);
                onSmartCallBack.onCall(action);
            }
        };
        handler.postDelayed(runnable,time);
        runnableMap.put(action,runnable);
    }

    /**
     * post to handler
     * @param action
     */
    public synchronized void post(int action){
        EssayRunnable runnable = new EssayRunnable(action)  {
            @Override
            public void call() {
                if (onSmartCallBack == null)
                    throw new RuntimeException("OnSmartCallBack can't be null");
                runnableMap.remove(action);
                onSmartCallBack.onCall(action);
            }
        };
        handler.post(runnable);
        runnableMap.put(action , runnable);
    }
    /**
     * 移除当前的callback
     * @param action
     */
    public void removeTask(int action){
        EssayRunnable runnable = runnableMap.get(action);
        if (runnable != null){
            handler.removeCallbacks(runnable);
        }
    }

    /**
     * clear all Runnable in  hashMap
     */
    public void clear(){
        while(runnableMap.keySet().iterator().hasNext()){
            handler.removeCallbacks(runnableMap.get(runnableMap.keySet().iterator().next()));
        }
    }

    /**
     * set the call back listener
     * when handler task is over
     */
    public void setSmartCallBack(OnSmartCallBack onSmartCallBack){
        this.onSmartCallBack = onSmartCallBack;
    }

    /**
     * 回调runnable的接口
     */
    public interface OnSmartCallBack{
        void onCall(int action);
    }


}
